const path = require("path");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); //压缩js
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //分离css
const OptimizeCSSPlugin = require("optimize-css-assets-webpack-plugin"); //压缩css
const { CleanWebpackPlugin } = require("clean-webpack-plugin"); //打包前清空
const copyWebpackPlugin = require("copy-webpack-plugin"); //复制静态资源
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
    .BundleAnalyzerPlugin; //性能分析
const { merge } = require("webpack-merge");
const webpackConfigBase = require("./webpack.base");

const webpackConfigProd = {
    mode: "production",
    module: {
        rules: []
    },
    plugins: [
        //压缩js
        new UglifyJsPlugin({
            uglifyOptions: {
                output: null,
                warnings: false,
                compress: {
                    drop_console: true, // 删除所有的 `console` 语句，可以兼容ie浏览器
                    collapse_vars: true, // 内嵌定义了但是只用到一次的变量
                    reduce_vars: true // 提取出出现多次但是没有定义成变量去引用的静态值
                }
            },
            cache: false,
            sourceMap: true,
            parallel: true //使用多进程并行运行来提高构建速度
        }),
        //打包前清空目录
        new CleanWebpackPlugin(),
        //分离css
        new MiniCssExtractPlugin({
            filename: "[name].[hash:8].css",
            chunkFilename: "[id].[hash:8].css"
        }),
        //压缩css
        new OptimizeCSSPlugin({
            cssProcessorOptions: { safe: true }
        }),
        //静态资源输出,将src目录下的assets文件夹复制到dist目录下
        new copyWebpackPlugin([
            {
                from: path.resolve(__dirname, "../src/assets"),
                to: "./assets",
                ignore: [".*"]
            }
        ])
        //npm run build 后会打开一个页面，性能分析
        //new BundleAnalyzerPlugin()
    ],
    optimization: {
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: "initial", //表示显示块的范围，有三个可选值：initial(初始块)、async(按需加载块)、all(全部块)，默认为all;
                    name: "vendor", //拆分出来块的名字(Chunk Names)，默认由块名和hash值自动生成；
                    enforce: true
                }
                /* utils: { // 抽离自己写的公共代码，utils 这个名字可以随意起
                             chunks: 'initial',
                             name: 'utils',  // 任意命名
                             minSize: 0    // 只要超出 0 字节就生成一个新包
                         }*/
            }
        }
    },
    stats: {
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false,
        hash: false
    }
};
module.exports = merge(webpackConfigBase, webpackConfigProd);
